package com.boot.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boot.mapper.ProductMapper;
import com.boot.pojo.Order;
import com.boot.pojo.Product;
import com.boot.result.Result;
import com.boot.scripts.LuaScriptLoader;
import com.boot.service.OrderService;
import com.boot.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author liyan
 * @description 针对表【order】的数据库操作Service实现
 * @createDate 2025-05-10 15:30:16
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
        implements OrderService {
    @Autowired
    private LuaScriptLoader luaScriptLoader;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OrderMapper orderMapper;

    public Result createOrder(int productId, int quantity, String userId) throws ExecutionException, InterruptedException {
        // 构造Redis key
        String stockKey = "product:stock:" + productId;
        String orderKey = "product:order:" + productId;
        // 执行Lua脚本扣减库存
        boolean success = luaScriptLoader.deductStock(
                stockKey, orderKey, userId, quantity);
        if (!success) {
            return Result.build(10003,"库存不足",null);
        }// 异步创建真实订单
        CompletableFuture<Result> future = asyncCreateOrder(productId, quantity, userId);
            Result result = future.get();
        System.out.println(result);
        return Result.success("下单成功");

    }

    @Async
    public  CompletableFuture<Result> asyncCreateOrder(Integer productId, int quantity, String userId) {
        Product product = productMapper.selectById(productId);
        if (product == null || product.getStatus() !=1)  {
            return CompletableFuture.completedFuture(Result.build(10004, "商品不存在或已下架", null));
        }
        if (product.getStock() < quantity) {
            return CompletableFuture.completedFuture(Result.build(10005, "库存不足", null));
        }
        Order order = new Order();
        order.setProductId(product.getId());
        order.setCode(userId);
        order.setStatus(1);
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(quantity)));
        System.out.println(order);
        int insertRow = orderMapper.insert(order);
        if (insertRow == 0) {
            return CompletableFuture.completedFuture(Result.build(10006, "新增订单失败", null));
        }
        return CompletableFuture.completedFuture(Result.build(200,"下单成功",null));
    }
}




